<template>
  <div class="container">
    <div class="userInfo">
      <img :src="userInfo.avatarUrl" alt="">
      <button v-if="userInfo.authorized == 0" open-type="getUserInfo" @click="authoriz">点击授权</button>
      <button v-if="userInfo.authorized == 1" @click="login">点击登录</button>
      <p v-if="userInfo.authorized == 2">{{userInfo.nickName}}</p>
      <year-progress></year-progress>
      <button v-if="userInfo.authorized == 2" @click="scanBook" class="btn">添加图书</button>
    </div>
  </div>
</template>

<script>
import config from '@/config'
import qcloud from 'wafer2-client-sdk'
import YearProgress from '@/common/YearProgress'
import {showSuccess} from '@/util'
export default {
  name: 'Center',
  components: {
    YearProgress
  },
  data () {
    return {
      userInfo: {
        avatarUrl: '/static/img/unlogin.png',
        nickName: '点击登录',
        authorized: 0
      }
    }
  },
  methods: {
    scanBook () {
      wx.scanCode({
        success: (res) => {
          console.log(res)
        }
      })
    },
    authoriz () {
      this.userInfo.authorized = 1
    },
    login (res) {
      console.log(res)
      qcloud.setLoginUrl(config.loginUrl)
      qcloud.login({
        success: (userInfo) => {
          showSuccess('登录成功')
          this.userInfo = userInfo
          this.userInfo.authorized = 2
          wx.setStorageSync('userInfo', userInfo)
        },
        fail: (err) => {
          console.log('登录失败', err)
        }
      })
    }
  },
  created () {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.userInfo = userInfo
      this.userInfo.authorized = 2
    }
  }
}
</script>

<style lang="scss" scoped>
  .container{
    padding: 0 30rpx;
    .userInfo{
      margin-top: 100rpx;
      text-align: center;
      img{
        width: 150rpx;
        height: 150rpx;
        margin: 20;
        border-radius: 50%;
      }
    }
  }
</style>
